package Client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

public class send extends Socket {

	private static final String SERVER_IP = "127.0.0.1";
	// private static final String SERVER_IP = "服务器IP";
	private static final int SERVER_PORT = 8899;

	private Socket client;

	private FileInputStream fis;

	private DataOutputStream dos;

	public send() throws Exception {
		super(SERVER_IP, SERVER_PORT);
		this.client = this;
	}

	public void sendFile() throws Exception {
		try {
			File file = new File(ClientVariable.file);
			if (file.exists()) {
				fis = new FileInputStream(file);
				dos = new DataOutputStream(client.getOutputStream());

				dos.writeUTF(file.getName());
				dos.flush();
				dos.writeLong(file.length());
				dos.flush();

				DataInputStream in = new DataInputStream(client.getInputStream());
				DataOutputStream out = new DataOutputStream(client.getOutputStream());
				out.writeUTF(ClientVariable.number);
				String z = in.readUTF();
				System.out.println(z);

				byte[] bytes = new byte[1024];
				int length = 0;
				long progress = 0;
				while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
					dos.write(bytes, 0, length);
					dos.flush();
					progress += length;
					System.out.print("| " + (100 * progress / file.length()) + "% |");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null)
				fis.close();
			if (dos != null)
				dos.close();
			client.close();
		}
	}

	/**
	 * 入口
	 * 
	 * @param args
	 */
	public void good() {
		try {
			send client = new send(); // 启动客户端连接
			client.sendFile(); // 传输文件
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}